package com.foreknow.elm.dao.impl;

import com.foreknow.elm.dao.OrderDetailetDao;
import com.foreknow.elm.po.Cart;
import com.foreknow.elm.po.OrderDetailet;
import com.foreknow.elm.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrderDetailetDaoImpl implements OrderDetailetDao {
    private Connection con = null;
    private PreparedStatement pst = null;
    private ResultSet rs = null;

    /**
     * 根据orderId查询订单明细
     * @param orderId
     * @return
     */
    @Override
    public List<OrderDetailet> getOrderDetailetById(Integer orderId) {
        List<OrderDetailet> list = new ArrayList<>();
        String sql = "select * from orderdetailet od left join food f on od.foodId = f.foodId where od.orderId=?";
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setInt(1,orderId);
            rs = pst.executeQuery();
            while (rs.next()) {
                OrderDetailet orderDetailet = new OrderDetailet();
                // 将查询到的orderDetailet数据存入orderDetailet对象中
                orderDetailet.setOdId(rs.getInt("odId"));
                orderDetailet.setOrderId(rs.getInt("orderId"));
                orderDetailet.setFoodId(rs.getInt("foodId"));
                orderDetailet.setQuantity(rs.getInt("quantity"));
                // 将orderDetailet对象存入订单明细list集合中
                list.add(orderDetailet);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 根据传来的购物车list集合向订单明细中添加数据
     * @param list
     * @return
     */
    @Override
    public int insertOrderDetailet(List<Cart> list) {
        String sql ="insert into orderdetailet(foodId,quantity) values(?,?)";
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            for (Cart cart : list) { // 对购物车list进行for循环
                // 将cart中的foodId和quantity添加到订单明细表中
                pst.setInt(1,cart.getFoodId());
                pst.setInt(2,cart.getQuantity());
                // 购物车list几个cart对象就添加几条
                pst.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(rs,pst);

        }
        return list.size();
    }
}
